<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2018/7/7
 * Time: 11:17
 */

//公共函数
namespace YourApp\util;

use GatewayWorker\Lib\Db;

define('SAVEPATH',dirname(__DIR__).'/media');


//utf-8转gbk
class Common
{
    static public function UTF8toGBK($string)
    {
        return iconv('utf-8', 'GBK', $string);
    }

    static public function getString($hex_string)
    {
        return self::GBK2UTF8(pack('H*', $hex_string));
    }
    static public function setString($string){
        return hex2bin(unpack('H*',self::UTF8toGBK($string))[1]);
    }
    static public function GBK2UTF8($string)
    {
        return iconv('GBK', 'utf-8', $string);
    }

    //获取校验码
    static public function calCheckSum($hex_string)
    {
        $cs = hexdec(substr($hex_string, 0, 2));
        $str_len = strlen($hex_string);
        for ($i = 2; $i < $str_len; $i += 2) {
            $cs ^= hexdec(substr($hex_string, $i, 2));
        }
        return bin2hex(pack('C',$cs));
    }
    private static function dealPath($path){
        if(is_null($path)){
            $path=SAVEPATH;
        }
        return rtrim('/\\',$path);
    }
    public static function saveFile($string,$name,$path=null){
        $path=self::dealPath($path);
        file_put_contents($path.'/'.$name,$string);
    }
    public static function getListFile($name,$path=null){
        $path=self::dealPath($path);
        $find=$path.'/'.$name;
        return glob($find);
    }
    public static function saveToSingle($lists,$name,$path=null){
        $path=self::dealPath($path);
        $f=fopen($path.$name,'w');
        foreach ($lists as $list){
            fwrite($f,file_get_contents($list));
            unlink($lists);
        }
        fclose($f);
        return $path.$name;
    }
    public static function isDebug(){
        return file_exists(__DIR__.'/env.lock');
    }

    public static function getFFmepgPid(){
        $shell='ps -u |grep ffmpeg';
        $preg_str="/.+ffmpeg.+rtmp:\/\/.+/i";
        $sl=shell_exec($shell);
        $sl=explode("\n",$sl);
        $sl=array_filter($sl,function($string)use($preg_str){
            return !!preg_match($preg_str,$string);
        });
        $pids=[];
        foreach ($sl as $str){
            $pid=preg_split("/\s+/",$str)[1];
            $pids[]=$pid;
        }
        return $pids;
    }
    public static function ComResponse($flow_id,$msg_id,$return){
        return bin2hex(pack('n',$flow_id)).$msg_id.bin2hex(pack('C',$return));
    }
}

